#include <sys_call.h>
#include <string.h>
#include <display.h>

static void split_args(char *arg_line, char **argv)
{
	int i = 0, flag = 1;
	int argc = 0;
	while (1) {
		if (arg_line[i] == '\0') {
			break;
		} else if (arg_line[i] == ' ') {
			arg_line[i] = '\0';
			flag = 1;
		} else if (flag == 1) {
			argv[argc++] = &arg_line[i];
			flag = 0;
		}
		i++;
	}
	argv[argc] = NULL;
}
int shell(void)
{
	char *argv[10];
	char cmd[20];
	int ret, pid;

	while(1) {
		printf("shell> ");
		sys_read_tty(cmd);

		/* Only Enter. */
		if (cmd[0] == '\0')
			continue;

		/* Split the arguments. */
		split_args(cmd, argv);

		if(strcmp(argv[0], "exit") == 0)
			return 0;

		pid = sys_fork();
		if(pid == 0) {
			ret = sys_exec(cmd, argv);
			if(ret != 0) {
				printf("error in exec!\n");
				sys_exit(0);
			}
		}
		sys_wait(0);
	}
}

int _start()
{
	shell();
	sys_exit(0);
}
